﻿using System;
using System.Data.Odbc;
using System.Windows.Forms;
using ORM;

namespace ORM_Sample
{
    public partial class FormMain : Form
    {
        private PersonsList _personsList;

        public FormMain()
        {
            InitializeComponent();
            PersonDb.DBConnection = new OdbcConnection(Properties.Settings.Default.OrmTestDbConnectionString);
            PersonDb.TableName = "Person";
            _personsList = PersonsList.GetPersonsList();
        }

        private void ButtonGetAllDataClick(object sender, EventArgs e)
        {
            _personsList = PersonsList.GetPersonsList();
            foreach (ListViewItem item in ListViewDb.Items)
                item.Remove();
            ListViewItem li;
            //var dateTimeBefore = DateTime.Now;
            _personsList.RefreshData();
            for (var i = 0; i < _personsList.Size; ++i)
            {
                li = new ListViewItem {Text = _personsList[i].FirstName};
                li.SubItems.Add(_personsList[i].LastName);
                li.SubItems.Add(_personsList[i].Age.ToString());
                ListViewDb.Items.Add(li);
            }
            //var dt = DateTime.Now - dateTimeBefore;
            //Text = dt + @" : " + _personsList.Size;
        }

        private void ButtonAddClick(object sender, EventArgs e)
        {
            var person = new Person 
            {
                FirstName = "FirstName" + _personsList.Size, 
                LastName = "LastName" + _personsList.Size, 
                Age = new Random().Next(0, 115)
            };
            _personsList.Add(person);
            ButtonGetAllData.PerformClick();
        }

        private void ButtonRemoveClick(object sender, EventArgs e)
        {
            if(_personsList.Size > 0) 
                _personsList.RemoveAt(_personsList.Size - 1);
            ButtonGetAllData.PerformClick();
        }
    }
}
